package com.nxy.cpfsfe.util;

import org.slf4j.Logger;
import org.slf4j.MDC;

import java.io.File;

/**
 * 日志工具类
 */
public class LogUtil {

    private static final String MDCKey = "ROUTINGKEY";

    /**
     * 获取异常堆栈信息
     * @param throwable
     * @return
     */
	public static String getStackTrace(Throwable throwable) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(throwable.getClass().getName());
        buffer.append(": ");
        buffer.append(throwable.getMessage());
        buffer.append('\n');
        for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
            buffer.append("\tat ");
            buffer.append(stackTraceElement.toString());
            buffer.append('\n');
        }
        if(throwable.getCause() != null)
            buffer.append(getStackTrace(throwable.getCause()));
        return buffer.toString();
    }

    /**
     * 获得日志文件路径
     * @param direction 业务方向
     * @param bizCode 业务编号
     * @return
     */
    public static String getLogFileName(String direction,String bizCode){
        String date = CommonUtil.getDate();
        String threadName = Thread.currentThread().getName();
        StringBuilder logFileName = new StringBuilder(date);
        String tranCode  = bizCode.replaceAll("\\.","");
        logFileName.append(File.separator).append(direction).append(File.separator).append(tranCode).append(File.separator).append(threadName);
        return logFileName.toString();
    }

    public void info(Logger logger, String logFileName, String logMsg, Object... logArgs){
        MDC.put(MDCKey,logFileName);
        logger.info(logMsg,logArgs);
        MDC.remove(MDCKey);
    }

    public void error(Logger logger, String logFileName, String logMsg, Exception e){
        MDC.put(MDCKey,logFileName);
        logger.error(logMsg,e);
        MDC.remove(MDCKey);
    }

    public void debug(Logger logger, String logFileName, String logMsg, Object... logArgs){
        MDC.put(MDCKey,logFileName);
        logger.debug(logMsg,logArgs);
        MDC.remove(MDCKey);
    }
	
}
